//
//  HTTPOperation.m
//  AirPoke
//
//  Created by Anshu Chimala on 7/7/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "HTTPOperation.h"


@implementation HTTPOperation

@synthesize targetURL = _targetURL;
@synthesize postParameters = _postParameters;
@synthesize successSelector = _successSelector;
@synthesize failureSelector = _failureSelector;
@synthesize delegate = _delegate;

-(id)init {
	if(self = [super init]) {
		_targetURL = nil;
		_successSelector = nil;
		_failureSelector = nil;
		_delegate = nil;
		_postParameters = [[NSMutableArray alloc] init];
	}
	return self;
}

-(void)addValue:(NSString *)value forPOSTParameter:(NSString *)param {
	[_postParameters addObject:[NSDictionary dictionaryWithObject:value forKey:param]];
}

-(void)main {
	NSMutableString *postString = [NSMutableString string];
	for(NSDictionary *dict in _postParameters) {
		NSString *param = [dict.allKeys objectAtIndex:0];
		NSString *value = [dict objectForKey:param];
		
		[postString appendString:
		 [NSString stringWithFormat:@"&%@=%@",
		  [param stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
		  [value stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
	}
	
	NSData *postData = nil;
	if(postString.length)
		postData = [[NSData alloc] initWithBytes:postString.UTF8String length:postString.length];
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
	request.URL = _targetURL;
	request.HTTPMethod = (postString.length ? @"POST" : @"GET");
	if(postString.length)
		request.HTTPBody = postData;
	
	NSError *error = nil;
	NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
	
	if(!_delegate) {
		if(postData)
			[postData release];
		[request release];
		return;
	}
	
	if(result && (!error || [error code] == 0))
		[_delegate performSelectorOnMainThread:_successSelector withObject:result waitUntilDone:YES];
	else
		[_delegate performSelectorOnMainThread:_failureSelector withObject:error waitUntilDone:YES];
	
	if(postData)
		[postData release];
	[request release];
}

-(void)dealloc {
	self.targetURL = nil;
	self.postParameters = nil;
	self.delegate = nil;
	
	[super dealloc];
}

@end
